//
//  YCPlayMusicView.m
//  YCSchool
//
//  Created by Yanglixia on 16/5/15.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//

#import "YCPlayMusicView.h"
#import <AVFoundation/AVFoundation.h>
#import "YCAudioStreamer.h"
#import "YCAudioPlayer.h"
#import "YCDownloadDataManager.h"
#import "EMVoiceConverter.h"

@interface YCPlayMusicView()<YCAudioStreamerDelegate>
{
    CGFloat _totalTime;
}
@property (nonatomic, strong ) UIActivityIndicatorView *activityIndicatorView;
@property (nonatomic, strong ) UILabel *label;

@end

@implementation YCPlayMusicView

@synthesize btnPlay = _btnPlay;
@synthesize sliderView = _sliderView;

- (UIButton *)btnPlay
{
    if (!_btnPlay)
    {
        _btnPlay = [UIButton buttonWithType:UIButtonTypeCustom];
        [_btnPlay addTarget:self action:@selector(onTouchButton) forControlEvents:UIControlEventTouchUpInside];
        [_btnPlay setImage:[UIImage imageNamed:@"strutPlay"] forState:UIControlStateNormal];
        [_btnPlay setImage:[UIImage imageNamed:@"strutStop"] forState:UIControlStateSelected];
    }
    return _btnPlay;
}

- (UILabel *)label
{
    if (!_label)
    {
        _label = [[UILabel alloc] init];
        _label.backgroundColor = [UIColor clearColor];
        _label.font = [UIFont systemFontOfSize:12];
        _label.textAlignment = NSTextAlignmentRight;
        _label.textColor = [UIColor yc_colorWithUInt:0x808080];
    }
    return  _label;
}

- (UIActivityIndicatorView *)activityIndicatorView
{
    if (!_activityIndicatorView)
    {
        _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _activityIndicatorView.hidesWhenStopped = YES;
    }
    return _activityIndicatorView;
}

- (UISlider *)sliderView
{
    if (!_sliderView)
    {
        _sliderView = [[UISlider alloc] init];
        [_sliderView addTarget:self action:@selector(processChanged) forControlEvents:UIControlEventValueChanged];
        [_sliderView setThumbImage:[UIImage imageNamed:@"strutSlider"] forState:UIControlStateNormal];
        _sliderView.enabled = NO;
    }
    return _sliderView;
}

- (void)setStringPath:(NSString *)stringPath
{
    _stringPath = stringPath;
}

- (instancetype)init
{
    if (self = [super init])
    {
        self.frame = CGRectMake(0, 0, kScreenWidth, 40);
        
        [self layout];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioStramerPause) name:@"audioPlayerPause" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioStramerStop) name:@"audioPlayerStop" object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [[YCAudioStreamer sharedStreamer] stop];
}

- (void)layout
{
    [self addSubview:self.btnPlay];
    [self addSubview:self.sliderView];
    [self addSubview:self.activityIndicatorView];
    [self addSubview:self.label];
    
    [self.btnPlay mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@0);
        make.centerY.equalTo(self);
        make.width.equalTo(@(30));
    }];
    
    [self.sliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.right.equalTo(self);
        make.left.equalTo(self.btnPlay.mas_right).offset(5);
        make.right.equalTo(self);
        make.height.equalTo(@(20));
    }];
    
    [self.activityIndicatorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self);
        make.right.equalTo(self.btnPlay.mas_left);
        make.width.equalTo(@(20));
    }];
    
    [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self);
        make.right.equalTo(@0);
        make.height.equalTo(@(16));
        make.width.equalTo(@(100));
    }];
}

- (void)onTouchButton
{
    ///下载通知downProgressChange
    
    if ([_stringPath rangeOfString:@".wav"].location != NSNotFound || [_stringPath rangeOfString:@".amr"].location != NSNotFound)
    {
        YCDownloadDataManager *manager = [YCDownloadDataManager sharedManager];
        
        NSURL *url = [NSURL URLWithString:_stringPath];
        
        [manager downloadDataWithURL:url completionHandlerCallBack:^(NSURLResponse *response, NSURL *filePath, YCDownloadDataManagerDataFrom datafrom, NSError *error) {
            
            if (!error) {
                
                [[YCAudioPlayer player] asyncPlayAMRFileWithPath:filePath.relativePath completion:^(NSError *error) {  }];
            } else {
                [SVProgressHUD showErrorWithStatus:@"下载语音失败"];
            }
            
        }];
    }
    else
    {
        [YCAudioStreamer sharedStreamer].delegate = self;
        if (!([[YCAudioStreamer sharedStreamer] isPlayingCurrentAudioWithURL:_stringPath] && [YCAudioStreamer sharedStreamer].tag == self.tag))
        {
            [[YCAudioStreamer sharedStreamer] stop];
            
            [YCAudioStreamer sharedStreamer].url = _stringPath;
            [[YCAudioStreamer sharedStreamer] setAudioMetadataWithURL:_stringPath];
            [[YCAudioStreamer sharedStreamer] play];
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioStramerprogressChanged:) name:@"progressChanged" object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioStramerproPlayGressChanged:) name:@"downProgressChanged" object:nil];
            
            YCLog(@"从新开始");
            _btnPlay.selected = YES;
            [YCAudioStreamer sharedStreamer].tag = self.tag;
        }
        else
        {
            if ([[YCAudioStreamer sharedStreamer] isPlaying])
            {
                [[YCAudioStreamer sharedStreamer] pause];
                [[NSNotificationCenter defaultCenter] removeObserver:self name:@"progressChanged" object:nil];
                YCLog(@"停止");
                _btnPlay.selected = NO;
            }
            else
            {
                [[YCAudioStreamer sharedStreamer] play];
                YCLog(@"开始");
                _btnPlay.selected = YES;
            }
        }
    }
}

- (void) audioStramerproPlayGressChanged:(NSNotification *)not
{
    NSDictionary *ps = not.object;
    
    CGFloat progress = [ps[@"value"] floatValue];
    self.sliderView.value = progress;
    
    _label.text = [NSString stringWithFormat:@"%@/%@",[YCAudioStreamer timeWithInteger:[YCAudioStreamer sharedStreamer].currentTime],[YCAudioStreamer timeWithInteger:[YCAudioStreamer sharedStreamer].totalTime]];
}

- (void) audioStramerprogressChanged:(NSNotification *)not
{
    NSDictionary *ps = not.object;
    
    CGFloat progress = [ps[@"value"] floatValue];
    if (progress < 1)
    {
        [self.activityIndicatorView startAnimating];
    }
    else
    {
        [self.activityIndicatorView stopAnimating];
    }
}

//暂停
- (void) audioStramerPause
{
    _btnPlay.selected = NO;
}

//停止
- (void) audioStramerStop
{
    _btnPlay.selected = NO;
    [_activityIndicatorView stopAnimating];
    _sliderView.value = 0;
    if (_totalTime <= 0.1)
    {
        _label.text = @"";
    }
    else
    {
        _label.text = [NSString stringWithFormat:@"00:00/%@",[YCAudioStreamer timeWithInteger:_totalTime]];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"progressChanged" object:nil];//下载通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"downProgressChanged" object:nil];//播放通知
}

//开始
- (void)audioStramerStartPlay
{
    _btnPlay.selected = YES;
    _label.text = [NSString stringWithFormat:@"%@/%@",[YCAudioStreamer timeWithInteger:[YCAudioStreamer sharedStreamer].currentTime],[YCAudioStreamer timeWithInteger:[YCAudioStreamer sharedStreamer].totalTime]];
    _totalTime = [YCAudioStreamer sharedStreamer].totalTime;
}

//播放完成
- (void)audioStramerFinishPlay
{
    _btnPlay.selected = NO;
    _sliderView.value = 0;
    if (_totalTime <= 0.1)
    {
        _label.text = @"";
    }
    else
    {
        _label.text = [NSString stringWithFormat:@"00:00/%@",[YCAudioStreamer timeWithInteger:_totalTime]];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"progressChanged" object:nil];//下载通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"downProgressChanged" object:nil];//播放通知
    
    [YCAudioStreamer sharedStreamer].url = nil;
    [[YCAudioStreamer sharedStreamer] setAudioMetadataWithURL:nil];
}

- (void)processChanged
{
    [[YCAudioStreamer sharedStreamer] seekToTime:_sliderView.value*[YCAudioStreamer sharedStreamer].totalTime];
}


@end
